package com.bdqn.bookshop.utils;



import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpRequest;
import org.springframework.web.multipart.MultipartFile;


/**
 * @author : 罗若然[LUO_RUO_RAN]
 * @date : 2020-07-25 15:51
 **/
public class FileUtil {

    /**
     * 获得当前请求的根url地址
     * @param request
     * @return
     */
    public  static    String   getHttpRootUrl(HttpServletRequest  request){
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        return  basePath;
    }


    /**
     * 保存文件
     * @param request
     * @param file
     * @param savePath
     * @param mappingUrl
     * @return
     */
    public   static    FileResult   saveFileToPath(HttpServletRequest  request, MultipartFile file,String savePath,String mappingUrl){
        return saveFileToPath(request, file, savePath, mappingUrl,null);
    }


    /**
     * 保存文件
     * @param request
     * @param file  接收文件对象
     * @param savePath  保存地址路径
     * @param mappingUrl  映射地址路径
     * @param newFileName  指定新文件名 不需要加后缀
     * @return
     */
    public   static    FileResult   saveFileToPath(HttpServletRequest  request, MultipartFile file, String savePath, String mappingUrl, String newFileName){
        File  saveFile =null;
        boolean  falg=false;
        try {
            if(file!=null&&!file.isEmpty()){
                String  originalName= file.getOriginalFilename();
                String  newName= (StringUtils.isNotBlank(newFileName) ?newFileName:System.currentTimeMillis())+originalName.substring(originalName.lastIndexOf("."));
                saveFile=getRealFile(request, savePath, newName);
                file.transferTo(saveFile);
                falg=true;

                String httpUrl=getHttpRootUrl(request);
                if(!httpUrl.endsWith("/"))  httpUrl+="/";

                //去除/开头
                if(mappingUrl.startsWith("/"))    mappingUrl=mappingUrl.substring(1);
                httpUrl+=mappingUrl;

                if(!httpUrl.endsWith("/"))  httpUrl+="/";
                httpUrl+=newName;
                return  new   FileResult(newName, saveFile, httpUrl, falg);
            }
        }catch (Exception e) {
            e.printStackTrace();
            if(saveFile!=null && saveFile.exists())  saveFile.delete();
        }
        return  null;
    }

    /**
     * 获得项目根路径
     * @param request
     * @return
     */
    public  static   String   getRootPath(HttpServletRequest  request){
        return   getRootPath(request.getSession());
    }
    public  static   String   getRootPath(HttpSession  session){
        //当前项目部署的所在位置根路径
        String  rootPath=session.getServletContext().getRealPath("");
        if(StringUtils.isBlank(rootPath)){  rootPath=session.getServletContext().getRealPath(File.separator);  }
        if(!rootPath.endsWith(File.separator))  rootPath+=File.separator;

        return  rootPath;
    }

    /**
     * 获得文件对象
     * @param request
     * @param savePath
     * @param fileName
     * @return
     */
    public  static  File    getRealFile(HttpServletRequest  request ,String savePath,String fileName){
        return getRealFile(request.getSession(),savePath,fileName) ;
    }

    public  static  File    getRealFile(HttpSession  session ,String savePath,String fileName){
        if(!savePath.startsWith("file:///")){
            //当前项目部署的所在位置根路径
            String  rootPath= getRootPath( session);
            //去除/开头
            if(savePath.startsWith(File.separator))    savePath=savePath.substring(1);
            //保存文件的绝对地址
            savePath =rootPath+savePath;

        }else{
            savePath=savePath.substring("file:///".length());
            File  f=new File(savePath);
            if(!f.exists())  f.mkdirs();
        }

        if(!savePath.endsWith(File.separator))  savePath+=File.separator;
        return new File(savePath+fileName);
    }


    /**
     * 删除文件的方法
     * @param request
     * @param fileName
     * @param savePath
     * @return
     */
    public  static   boolean   deleteFile(HttpServletRequest  request, String fileName,String savePath){
        return  deleteFile(request.getSession(), fileName, savePath);
    }

    public  static   boolean   deleteFile(HttpSession  session, String fileName,String savePath){
        //当前项目部署的所在位置根路径
        try {

            String  rootPath= getRootPath( session);
            if(fileName.startsWith("http://")||fileName.startsWith("https://")){
                fileName=fileName.substring(fileName.lastIndexOf("/")+1);
            }
            File  file=getRealFile(session, savePath, fileName);
            if(file.exists())   return file.delete();
            return  true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  false;
    }

    /**
     * 修改文件名
     * @param img
     * @return
     */
    public static  String renameFile(String savePath,String img){
        //修改文件后缀_temp
        String newFileName = img.replace("_temp","");
        //判断传过来的路径是否存在file:///
        if(savePath.indexOf("file:///")>-1){
            savePath=savePath.substring(savePath.indexOf(":")+4);
        }
        //构建文件对象
        File file = new File(savePath,img);
        //判断文件是否存在
        if(file.exists()){
            //重命名
            file.renameTo(new File(savePath,newFileName));
        }
        return newFileName;
    }

    /**
     * 定时清理文件
     */
    public static void deleteFiles(String savePath) {
        //判断传过来的路径是否存在file:///
        if(savePath.indexOf("file:///")>-1){
            savePath=savePath.substring(savePath.indexOf(":")+4);
        }
        //构建文件对象
        File file = new File(savePath);
        //判断文件对象是否为空
        if(file!=null){
            //获取文件对象里所有文件
            File[] files = file.listFiles();
            //循环删除
            for (File f : files) {
                //判断文件后缀是_temp
                if(f.getName().endsWith("_temp")){
                    f.delete();
                }
            }
        }
    }

}
